package com.smt.take.ui.activity

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.smt.take.R
import com.smt.take.model.beans.Seller
import com.smt.take.ui.adapter.CartRvAdapter
import com.smt.take.ui.fragment.CommentsFragment
import com.smt.take.ui.fragment.GoodsFragment
import com.smt.take.ui.fragment.SellerFragment
import com.smt.take.utils.PriceFormater
import com.smt.take.utils.TakeOutApp
import kotlinx.android.synthetic.main.activity_add_edit_receipt_address.*
import kotlinx.android.synthetic.main.activity_business.*
import kotlinx.android.synthetic.main.activity_business.ib_back

class BusinessActivity : BaseActivity() {

    var hasSelectInfo = false
    lateinit var seller: Seller
    lateinit var rvCart: RecyclerView
    private var bottomSheetView: View? = null
    lateinit var adapter: CartRvAdapter
    private val titles = listOf("商品", "商家", "评论")
    val fragments = listOf(GoodsFragment(), SellerFragment(), CommentsFragment())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_business)
        // 判断设备是否有虚拟按键
        if (checkDeviceHasNavigationBar(this)) {
            fl_Container.setPadding(0, 0, 0, 48.dp2px())
        }
        processIntent()
        initView()
    }

    @SuppressLint("SetTextI18n")
    private fun processIntent() {
        if (intent.hasExtra("hasSelectInfo")) {
            hasSelectInfo = intent.getBooleanExtra("hasSelectInfo", false)
            seller = intent.getSerializableExtra("seller") as Seller
            tvDeliveryFee.text = "另需配送费" + PriceFormater.format(seller.deliveryFee.toFloat())
            tvSendPrice.text = PriceFormater.format(seller.sendPrice.toFloat()) + "起送"
        }
    }

    private fun initView() {
        ib_back.setOnClickListener { finish() }
        vp.adapter = BusinessFragmentPagerAdapter()
        tabs.setupWithViewPager(vp)// tableLayout绑定ViewPager
        bottom.setOnClickListener {
            showOrHideCart()
        }
        tvSubmit.setOnClickListener {
            val intent = Intent(this,ConfirmOrderActivity::class.java)
            startActivity(intent)
        }
    }

    fun showOrHideCart() {
        if (bottomSheetView == null) {
            // 加载要显示的布局
            bottomSheetView = LayoutInflater.from(this)
                .inflate(R.layout.cart_list, window.decorView as ViewGroup, false)
            rvCart = bottomSheetView!!.findViewById(R.id.rvCart)
            rvCart.layoutManager = LinearLayoutManager(this)
            adapter = CartRvAdapter(this)
            rvCart.adapter = adapter
            val tvClear = bottomSheetView!!.findViewById<TextView>(R.id.tvClear)
            tvClear.setOnClickListener {
                val builder = AlertDialog.Builder(this)
                builder.setTitle("确认都不吃吗?")
                builder.setPositiveButton("是,都不吃了") { dialog, which ->
                    // 开始清理购物车,把购物车中的数量重置为0
                    val goodsFragment: GoodsFragment = fragments[0] as GoodsFragment
                    goodsFragment.presenter.clearCart()
                    adapter.notifyDataSetChanged()
                    // 关闭购物车
                    showOrHideCart()
                    // 刷新右侧
                    goodsFragment.goodsAdapter.notifyDataSetChanged()
                    // 清空所有红点
                    clearRedDot()
                    goodsFragment.goodsTypeAdapter.notifyDataSetChanged()
                    // 刷新下方底部购物栏
                    updateCartUI()
                    // 清空缓存
                    TakeOutApp.instance.clearCacheSelectedInfo(seller.id.toInt())
                }
                builder.setNegativeButton("不,我还要吃") { dialog, which -> }
                builder.show()
            }
        }
        // 判断BottomSheetLayout内容是否显示
        if (bottomSheetLayout.isSheetShowing) {
            // 关闭内容显示
            bottomSheetLayout.dismissSheet()
        } else {
            val goodsFragment: GoodsFragment = fragments[0] as GoodsFragment
            val cartList = goodsFragment.presenter.getCartList()
            adapter.setCartListData(cartList)
            // 显示BottomSheetLayout里面的内容
            if (cartList.size > 0) {
                bottomSheetLayout.showWithSheetView(bottomSheetView)
            }
        }
    }

    private fun clearRedDot() {
        val goodsFragment = fragments[0] as GoodsFragment
        val goodsTypeList = goodsFragment.presenter.goodsTypeList
        for (i in 0 until goodsTypeList.size) {
            val goodsListBean = goodsTypeList[i]
            goodsListBean.redDotCount = 0
        }
    }
    

    inner class BusinessFragmentPagerAdapter : FragmentPagerAdapter(supportFragmentManager) {

        override fun getPageTitle(position: Int): CharSequence {
            return titles[position]
        }

        override fun getCount(): Int {
            return titles.size
        }

        override fun getItem(position: Int): Fragment {
            return fragments[position]
        }
    }

    // 克隆添加按钮
    fun addImageButton(ib: ImageButton, width: Int, height: Int) {
        fl_Container.addView(ib, width, height)
    }

    // 获取底部购物绝对位置
    fun getCartLocation(): IntArray {
        val destLocal = IntArray(2)
        imgCart.getLocationInWindow(destLocal)
        return destLocal
    }

    // 更新购物车UI
    fun updateCartUI() {
        // 更新数量 更新总价
        var count = 0
        var countPrice = 0.0f
        // 哪些商品属于购物车
        val goodsFragment: GoodsFragment = fragments[0] as GoodsFragment
        val cartList = goodsFragment.presenter.getCartList()
        for (i in 0 until cartList.size) {
            val goodsDetailsBean = cartList[i]
            count += goodsDetailsBean.count
            countPrice += goodsDetailsBean.count * goodsDetailsBean.newPrice.toFloat()
        }
        if (count > 0) {
            tvSelectNum.visibility = View.VISIBLE
        } else {
            tvSelectNum.visibility = View.GONE
        }
        tvSelectNum.text = count.toString()
        tvCountPrice.text = PriceFormater.format(countPrice)
        if (countPrice >= seller.sendPrice.toFloat()) {
            tvSubmit.visibility = View.VISIBLE
            tvSendPrice.visibility = View.GONE
        }else{
            tvSubmit.visibility = View.GONE
            tvSendPrice.visibility = View.VISIBLE
        }
    }
}